package com.fyzk.base;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.fyzk.utils.LogUtil;
import com.tyjc.lottery.R;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Timer;
import java.util.TimerTask;

@ContentView(R.layout.base_web_framelayout)
public class BaseWebFragment extends BaseFragment {

    @ViewInject(R.id.powerlist_webview)
    WebView webView;
    @ViewInject(R.id.powerlist_progress)
    ProgressBar progressbar;
    private int type;
    private String url;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }

    public static BaseWebFragment newInstance(String url, int type) {
        Bundle args = new Bundle();
        BaseWebFragment fragment = new BaseWebFragment();
        args.putString("url", url);
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        progressbar.setVisibility(View.GONE);
        type = getArguments().getInt("type", 0);
        url = getArguments().getString("url");
        webView.loadUrl(url);
        webView.setVisibility(View.INVISIBLE);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        settings.setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        settings.setSupportZoom(true);//是否可以缩放，默认true
        settings.setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        settings.setAppCacheEnabled(false);//是否使用缓存
        settings.setDomStorageEnabled(true);//DOM Storage
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //该方法解决的问题是打开浏览器不调用系统浏览器，直接用webview打开
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.e("fjl", "onProgress>" + view.getUrl());
                super.onProgressChanged(view, newProgress);
                evaluateJavascript(view);
                if (view.getUrl().contains("a=login")) {
                    view.goBack();
                }
                if (canJump && view.getUrl().contains("detail")) {
                    view.goBack();
                    canJump = false;
                    RealTimeScoreWebViewActivity.actionStart(getContext(), "详情", view.getUrl(), type);
                }
            }
        });
        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    evaluateTimerJavascript(webView);
                }
                return false;
            }
        });
        startTimer(webView);
    }

    private boolean canJump = true;

    @Override
    public void onResume() {
        super.onResume();
        canJump = true;
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            event.getDeviceId();
            return super.shouldOverrideKeyEvent(view, event);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            webView.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
            //在加载完成之后对网页中内容进行隐藏
            //getElementById()
            //getElementsByName()
            //getElementsByTagName()
//            String javascript = getCommonJs();
//            //创建方法
//            view.loadUrl(javascript);
//            view.loadUrl("javascript:hideOther();");
            evaluateJavascript(view);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("dsadasda", "dasdasdasad");
        }
    }

    public void evaluateJavascript(WebView view) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                view.evaluateJavascript("document.documentElement.getElementsByClassName('floatLayer-container')[0].style.display = 'none'", null);
                view.evaluateJavascript("document.documentElement.getElementsByClassName('global-tabbar')[0].style.display = 'none'", null);
                view.evaluateJavascript("document.documentElement.getElementsByClassName('head-zone')[0].style.display = 'none'", null);
                view.evaluateJavascript("document.documentElement.getElementsByClassName('refresh-box')[0].style.display = 'none'", null);
                view.evaluateJavascript("document.documentElement.getElementsByClassName('switch-box')[0].style.display = 'none'", null);
                if (type == 0) {
                    view.evaluateJavascript("document.documentElement.getElementsByClassName('s-wrapper')[0].getElementsByTagName('li')[1].style.display = 'none'", null);
                    view.evaluateJavascript("document.documentElement.getElementsByClassName('s-wrapper')[0].getElementsByTagName('li')[4].style.display = 'none'", null);
                    view.evaluateJavascript("document.documentElement.getElementsByClassName('s-wrapper')[0].getElementsByTagName('li')[5].style.display = 'none'", null);
                    view.evaluateJavascript("document.documentElement.getElementsByClassName('s-wrapper')[0].getElementsByTagName('li')[6].style.display = 'none'", null);
                    view.evaluateJavascript("document.documentElement.getElementsByClassName('s-wrapper')[0].getElementsByTagName('li')[7].style.display = 'none'", null);
                } else {
                    view.evaluateJavascript("document.documentElement.getElementsByClassName('item-tab item-tab-base')[0].getElementsByTagName('li')[2].style.display = 'none'", null);
                }
            }
        });
    }

    private Timer timer = null;//计时器
    private TimerTask task = null;

    private void evaluateTimerJavascript(WebView view) {
        evaluateJavascript(view);
        stopTimer();
        startTimer(view);
    }

    int number = 10000;//设置运行五次

    private void startTimer(WebView view) {
        timer = new Timer();
        task = new TimerTask() {
            int count = 0;    //从0开始计数，每运行一次timertask次数加一，运行制定次数后结束。

            @Override
            public void run() {
                if (count < number) {
                    evaluateJavascript(view);
                } else {
                    timer.cancel();
                }
                count++;
            }
        };
        //100ms执行一次
        timer.schedule(task, 100, 100);
    }

    private void stopTimer() {
        if (timer != null)
            timer.cancel();
        timer = null;//据说这样不会自动跳出软件
    }

    @Override
    public void onDetach() {
        stopTimer();
        super.onDetach();
    }

    @Override
    public void onDestroy() {
        stopTimer();
        super.onDestroy();
    }

    public boolean canBack() {
        if (webView != null) {
            return webView.canGoBack();
        }
        return false;
    }


    public void back() {
        if (webView != null) {
            webView.goBack();
        }
    }

}
